<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 封装一个jsonp函数
        function jsonp({ url, params, callback }) {
            return new Promise((resolve, reject) => {
                // 定义回调函数
                window[callback] = function (data) {
                    resolve(data)
                }
                const script = document.createElement('script') // 创建script标签
                params = { ...params, callback }
                const arr = []
                for (const key in params) {
                    if (params.hasOwnProperty(key)) { // 判断当前key是否是params对象自身的属性，有可能会是原型上的属性，所以需要判断一下
                        arr.push(`${key}=${params[key]}`)
                    }
                }
                url += `?${arr.join('&')}` // 拼接参数
                script.async = true
                script.src = url
                document.body.appendChild(script)
                script.onload = () => {
                    document.body.removeChild(script)
                }
            })
        }
        // 使用jsonp
        jsonp({
            url: 'http://127.0.0.1:8081/user',
            params: { id: '1' },
            callback: 'getUserData'
        }).then(res => {
            console.log('res:', res)
        })
    </script>
</body>

</html>